package com.iflytek.iot.common.model;

import com.iflytek.iot.common.constants.BaseErrorCode;
import com.iflytek.iot.common.constants.IMessage;
import com.iflytek.iot.common.utils.DateUtils;

/**
 * @author yu 2018/11/30.
 */
public class Result<T> extends BaseResult<T> {


    /**
     * Usage:
     * Result.ok().setResult("hello")
     * 返回结果时携带数据
     * @param data
     * @return
     */
    public Result<T> setResult(T data) {
        this.setData(data);
        return this;
    }

    /**
     * 通用成功响应(默认响应码为0000)
     *
     * @return
     */
    public static Result ok() {
        return ok(BaseErrorCode.common.SUCCESS);
    }

    /**
     * 自动义成功响应，一般定义枚举实现IMessage
     * @param msg
     * @param <T>
     * @return
     */
    public static <T> Result<T> ok(IMessage msg) {
        return baseCreate(msg.getErrCode(), msg.getErrMsg(), true);
    }

    /**
     * 通用服务器未知异常(默认响应码9999)
     *
     * @return
     */
    public static Result fail() {
        return fail(BaseErrorCode.common.UNKNOWN_ERROR);
    }

    /**
     * 失败响应
     *
     * @param message IMessage
     * @return
     */
    public static Result fail(IMessage message) {
        return fail(message.getErrCode(), message.getErrMsg());
    }

    /**
     * 失败响应
     *
     * @param code 错误响应码
     * @param msg  错误信息
     * @return
     */
    public static Result fail(String code, String msg) {
        return baseCreate(code, msg, false);
    }


    private static <T> Result<T> baseCreate(String code, String msg, boolean success) {
        Result result = new Result();
        result.setCode(code);
        result.setSuccess(success);
        result.setMessage(msg);
        result.setTimestamp(DateUtils.nowStrTime());
        return result;
    }
}
